package com.learning.js_work1;


import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;

import java.io.IOException;


@WebFilter(filterName = "MyFilter", urlPatterns = "/*")
public class LonginFilter implements Filter {

    // 定义一个排除列表，包含不需要登录就能访问的路径
    private static final String[] exclude_paths = {"/login", "/register", "/public","/"};
    // 检查当前请求路径是否在排除列表中
    private boolean isExcludedPath(String path) {
        for (String excludedPath : exclude_paths) {
            if (path.endsWith(excludedPath)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request= (HttpServletRequest)servletRequest ;
        String username= (String)request.getSession().getAttribute("username");//利用会话对象获取信息
        if (isExcludedPath(request.getRequestURI())) {
            filterChain.doFilter(request, servletResponse); // 如果是排除的路径，则直接通过
        }
        else if ("".equals(username)||username==null) {
            request.getRequestDispatcher("/login.jsp").forward(request,servletResponse);//不是排除路径且没登录，拦截，跳转登录页面
        }else {
            filterChain.doFilter(request,servletResponse); //放行
        }
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}